package com.hudilao.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//新增员工时抛出异常，构建全局异常处理器
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    //异常处理方法
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage());

        //要求用户名唯一的约束
        //用户名重复的异常情况
        if(ex.getMessage().contains("Duplicate entry")){
            String[]split = ex.getMessage().split(" ");
            String message = "" + split[2] + "已存在,请更换一个吧！";
            return R.error(message);
        }
        return R.error("未知错误出现");
    }
}
